﻿using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace EdlinSoftware.RegexTester.Code
{
    internal class TextLinesStorage
    {
        #region Methods

        public string[] GetLinesFromFile(string fileName)
        {
            fileName = GetFullPath(fileName);

            using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(fs))
                {
                    var result = new List<string>();
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        result.Add(line);
                    }
                    return result.ToArray();
                }
            }
        }

        private static string GetFullPath(string fileName)
        {
            fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location), fileName);
            return fileName;
        }

        public void SaveLinesToFile(string fileName, IEnumerable<string> lines)
        {
            fileName = GetFullPath(fileName);

            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    foreach (string line in lines)
                    {
                        writer.WriteLine(line);
                    }
                }
            }
        }

        #endregion
    }
}
